﻿using System;
using System.Collections.Generic;
using System.Dynamic;

namespace BusinessLayer
{
    /// <summary>
    /// The polygon.
    /// </summary>
    public class Polygon
    {
        /// <summary>
        /// Points.
        /// </summary>
        public List<Point> Points { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="Polygon"/> class.
        /// </summary>
        public Polygon(List<Point> pts)
        {
            this.Points = pts;
        }

        /// <summary>
        /// Checking is the point inside the polygon?
        /// </summary>
        public bool Contains(Point point)
        {
            List<Point> pts = new List<Point>(); //polygon's and vertical's intersection points
            for (int i = 0; i < this.Points.Count - 1; i++)
            {
                if ((this.Points[i].X <= point.X && point.X <= this.Points[i + 1].X) || 
                    (this.Points[i + 1].X <= point.X && point.X <= this.Points[i].X)) //if point.x is between points[i].x and points[i+1].x
                {
                    //y = ax + b
                    if (this.Points[i].X.Equals(this.Points[i + 1].X))
                    {
                        if ((this.Points[i].Y <= point.X && point.Y <= this.Points[i + 1].Y) ||
                            (this.Points[i + 1].Y <= point.Y && point.Y <= this.Points[i].Y)) //point is on the edge
                            return true;
                    }
                    else
                    {
                        double a = (this.Points[i].Y - this.Points[i + 1].Y)/(this.Points[i].X - this.Points[i + 1].X);
                        double b = this.Points[i].Y - a*this.Points[i].X;
                        if ((a*point.X + b).Equals(point.Y)) //point is on the polygon's edge
                            return true;
                        pts.Add(new Point(point.X, a*point.X + b));
                    }
                }
            }

            int below = 0;//points in pts below point
            foreach (var pt in pts)
                if (pt.Y < point.Y)
                    below++;
            if (below % 2 == 0)
                return false;
            else
                return true;
        }
    }
}
